<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="88px"
    >
      <el-form-item label="服务商名称" prop="agentName">
        <el-input
          v-model="queryParams.agentName"
          placeholder="请输入服务商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务商手机号" prop="userName" label-width="100px">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入服务商手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="上级代理商" prop="parentName">
        <el-input
          v-model="queryParams.parentName"
          placeholder="请输入上级服务商名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item label="实名状态" prop="isRealName">
        <el-select
          v-model="queryParams.isRealName"
          placeholder="请选择实名状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in is_real_name"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务商状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择服务商状态"
          clearable
          style="width: 200px"
        >
          <el-option
            v-for="dict in agent_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['agent:agent:add']"
          >新增</el-button
        >
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['agent:agent:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['agent:agent:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['agent:agent:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="agentList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="服务商名称"
        align="center"
        width="150"
        prop="agentName"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="用户名"
        align="center"
        width="150"
        prop="userName"
        v-if="columns[1].visible"
      />

      <el-table-column
        label="云商名称"
        align="center"
        prop="grade"
        width="200"
        v-if="columns[11].visible"
      >
        <template #default="scope">
          <el-select
            v-model="scope.row.providerId"
            placeholder="请选择默认插件"
            clearable
            @change="ySChange(scope.row)"
            style="width: 200px"
          >
            <el-option
              v-for="item in ysList"
              :key="item.providerId"
              :label="item.cloudName"
              :value="item.providerId"
            />
          </el-select>
          <!-- {{scope.row.cloudName}} -->
        </template>
      </el-table-column>
      <el-table-column
        label="代理商等级"
        align="center"
        prop="grade"
        width="150"
        v-if="columns[2].visible"
      >
        <template #default="scope">
          <dict-tag :options="agent_grade" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column
        label="代理商分润比例"
        align="center"
        width="150"
        prop="ratio"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="代理商层级"
        align="center"
        prop="grade"
        width="150"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="团队机器总数"
        align="center"
        width="150"
        prop="machineNumber"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="团队激活总数"
        align="center"
        width="150"
        prop="activeNumber"
        v-if="columns[5].visible"
      />
      <el-table-column
        label="实名状态"
        align="center"
        prop="isRealName"
        width="150"
        v-if="columns[6].visible"
      >
        <template #default="scope">
          <dict-tag :options="is_real_name" :value="scope.row.isRealName" />
        </template>
      </el-table-column>
      <el-table-column
        label="等级到期时间"
        align="center"
        prop="expireTime"
        width="180"
        v-if="columns[7].visible"
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.expireTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="分润钱包"
        align="center"
        prop="wallet"
        width="150"
        v-if="columns[8].visible"
      />
      <el-table-column
        label="服务商状态"
        align="center"
        prop="status"
        width="150"
        v-if="columns[9].visible"
      >
        <template #default="scope">
          <dict-tag :options="agent_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="上级代理商"
        align="center"
        prop="parentName"
        width="150"
        v-if="columns[10].visible"
      />
      <el-table-column
        label="注册时间"
        width="150"
        align="center"
        prop="createTime"
      />
      <el-table-column label="操作" align="center" fixed="right">
        <template #default="scope">
          <el-dropdown>
            <el-button link type="primary" icon="Filter">更多</el-button>
            <template #dropdown>
              <el-dropdown-menu class="no-hover">
                <el-dropdown-item @click="handleViewDetail(scope.row)"
                  >预览</el-dropdown-item
                >
                <el-dropdown-item
                  @click="handleUpdate(scope.row)"
                  :disabled="!hasPermi('agent:agent:edit')"
                  >修改</el-dropdown-item
                >
                <el-dropdown-item
                  @click="handleDelete(scope.row)"
                  :disabled="!hasPermi('agent:agent:remove')"
                  >删除</el-dropdown-item
                >
                <el-dropdown-item @click="handleAddBankCard(scope.row)"
                  >添加银行卡</el-dropdown-item
                >
                <el-dropdown-item @click="handleViewBill(scope.row)"
                  >账单</el-dropdown-item
                >
                <el-dropdown-item @click="handleConfigRatio(scope.row)"
                  >配置分润</el-dropdown-item
                >
                <el-dropdown-item @click="handleResetPassword(scope.row)"
                  >重置密码</el-dropdown-item
                >
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改代理商信息对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="agentRef" :model="form" :rules="rules">
        <el-tabs type="border-card" v-model="modifyData">
          <el-tab-pane label="基本信息" name="contactName">
            <el-form-item label="服务商名称" prop="agentName">
              <el-input
                v-model="form.agentName"
                placeholder="请输入服务商名称"
              />
            </el-form-item>

            <el-form-item label="服务商电话" prop="contactPhone">
              <el-input
                v-model="form.contactPhone"
                placeholder="请输入服务商电话"
              />
            </el-form-item>
            <el-form-item label="服务商密码" prop="password">
              <el-input
                v-model="form.password"
                placeholder="请输入服务商登录密码"
                type="password"
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="结算信息" name="settle">
            <el-form-item label="服务商姓名" prop="contactName">
              <el-input
                v-model="form.contactName"
                placeholder="请输入服务商姓名"
              />
            </el-form-item>
            <el-form-item label="银行账户" prop="bankAccount">
              <el-input
                v-model="form.bankAccount"
                placeholder="请输入银行卡号"
              />
            </el-form-item>
            <el-form-item label="开户类型" prop="accountType">
              <el-radio-group v-model="form.accountType">
                <el-radio
                  v-for="dict in account_type"
                  :key="dict.value"
                  disabled
                  :value="parseInt(dict.value)"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
            <el-form-item label="开户行" prop="bankName">
              <el-select
                v-model="form.bankName"
                placeholder="请选择开户行"
                :loading="bankLoading"
                @change="handleBankChange"
              >
                <el-option
                  v-for="bank in bankListData"
                  :key="bank.id"
                  :label="bank.name"
                  :value="bank.name"
                ></el-option>
              </el-select>
              <div
                v-if="bankListData.length === 0"
                style="color: #999; font-size: 12px"
              >
                银行列表为空，请检查API
              </div>
            </el-form-item>
            <el-form-item label="开户支行" prop="provinceBranchName">
              <el-input
                v-model="form.provinceBranchName"
                placeholder="请输入开户支行"
                :disabled="!form.bankName"
              />
            </el-form-item>

            <el-form-item label="开户行省" prop="province">
              <el-select
                v-model="form.province"
                placeholder="请选择省份"
                @change="handleProvinceChange"
                :loading="districtLoading"
              >
                <el-option
                  v-for="province in provinceList"
                  :key="province.id"
                  :label="province.name"
                  :value="province.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开户行市" prop="city">
              <el-select
                v-model="form.city"
                placeholder="请选择城市"
                @change="handleCityChange"
                :disabled="!form.province"
                :loading="cityLoading"
              >
                <el-option
                  v-for="city in cityList"
                  :key="city.id"
                  :label="city.name"
                  :value="city.name"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="开户行区" prop="district">
              <el-select
                v-model="form.district"
                placeholder="请选择区县"
                :disabled="!form.city"
                :loading="districtDetailLoading"
              >
                <el-option
                  v-for="district in districtList"
                  :key="district.id"
                  :label="district.name"
                  :value="district.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="实名认证" name="realname">
            <el-form-item label="身份证号" prop="cardNumber">
              <el-input
                v-model="form.cardNumber"
                placeholder="请输入身份证号"
              />
            </el-form-item>
            <el-form-item label="身份证正面照片" prop="cardFrontUrl">
              <el-upload
                ref="cardFrontUploadRef"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :file-list="cardFrontFileList"
                :on-change="handleCardFrontChange"
                :on-remove="handleCardFrontRemove"
                :limit="1"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleCardFrontRemove(file)"
                      >
                        <el-icon><delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="身份证反面照片" prop="cardBackUrl">
              <el-upload
                ref="cardBackUploadRef"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :file-list="cardBackFileList"
                :on-change="handleCardBackChange"
                :on-remove="handleCardBackRemove"
                :limit="1"
                accept="image/*"
              >
                <el-icon><Plus /></el-icon>
                <template #file="{ file }">
                  <div>
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt=""
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <el-icon><zoom-in /></el-icon>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleCardBackRemove(file)"
                      >
                        <el-icon><delete /></el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
            <el-form-item label="发证时间" prop="cardIssueDate">
              <el-date-picker
                v-model="form.cardIssueDate"
                type="date"
                placeholder="请选择发证时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="证件到期时间" prop="cardExpireDate">
              <el-date-picker
                v-model="form.cardExpireDate"
                type="date"
                placeholder="请选择证件到期时间"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-tab-pane>
          <!-- <el-tab-pane label="配置" name="confirm">
            <el-form-item label="是否允许处理商城订单发货" prop="isOrder">
            <el-radio-group v-model="form.isOrder">
              <el-radio
                v-for="dict in sys_yes_no"
                :key="dict.value"
                :value="parseInt(dict.value)"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          </el-tab-pane> -->
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="prevTab" v-if="modifyData !== 'contactName'"
            >上一步</el-button
          >
          <el-button
            type="primary"
            @click="nextTab"
            v-if="modifyData !== 'realname'"
          >
            下一步
          </el-button>
          <el-button
            type="success"
            @click="submitForm"
            v-if="modifyData === 'realname'"
          >
            确 定
          </el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="图片预览"
      width="800px"
      append-to-body
    >
      <img
        :src="dialogImageUrl"
        style="display: block; max-width: 100%; margin: 0 auto"
      />
    </el-dialog>

    <!-- 新增银行卡对话框 -->
    <el-dialog
      :title="bankCardTitle"
      v-model="bankCardOpen"
      width="800px"
      append-to-body
    >
      <el-form
        ref="bankCardRef"
        :model="bankCardForm"
        :rules="bankCardRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="bankCardForm.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="银行卡号" prop="accountNumber">
              <el-input
                v-model="bankCardForm.accountNumber"
                placeholder="请输入银行卡号"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提现类型" prop="withdrawalType">
              <el-input value="对私" disabled placeholder="对私" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否默认" prop="isDefault">
              <el-select
                v-model="bankCardForm.isDefault"
                placeholder="请选择是否默认"
                style="width: 100%"
              >
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="开户行" prop="openingBankName">
              <el-select
                v-model="bankCardForm.openingBankName"
                placeholder="请选择开户行"
                :loading="bankLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="bank in bankListData"
                  :key="bank.id"
                  :label="bank.name"
                  :value="bank.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开户支行" prop="provinceBranchName">
              <el-input
                v-model="bankCardForm.provinceBranchName"
                placeholder="请输入开户支行"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="开户行省" prop="provinceName">
              <el-select
                v-model="bankCardForm.provinceName"
                placeholder="请选择省份"
                @change="handleBankCardProvinceChange"
                :loading="districtLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="province in provinceList"
                  :key="province.id"
                  :label="province.name"
                  :value="province.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户行市" prop="cityName">
              <el-select
                v-model="bankCardForm.cityName"
                placeholder="请选择城市"
                @change="handleBankCardCityChange"
                :disabled="!bankCardForm.provinceName"
                :loading="cityLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="city in cityList"
                  :key="city.id"
                  :label="city.name"
                  :value="city.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="开户行区" prop="districtName">
              <el-select
                v-model="bankCardForm.districtName"
                placeholder="请选择区县"
                :disabled="!bankCardForm.cityName"
                :loading="districtDetailLoading"
                style="width: 100%"
              >
                <el-option
                  v-for="district in districtList"
                  :key="district.id"
                  :label="district.name"
                  :value="district.name"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelBankCard">取 消</el-button>
          <el-button type="primary" @click="submitBankCard">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 配置分润比例对话框 -->
    <el-dialog
      :title="ratioTitle"
      v-model="ratioOpen"
      width="500px"
      append-to-body
    >
      <el-form
        ref="ratioRef"
        :model="ratioForm"
        :rules="ratioRules"
        label-width="120px"
      >
        <el-form-item label="代理商名称">
          <el-input v-model="ratioForm.agentName" disabled />
        </el-form-item>
        <el-form-item label="分润比例" prop="ratio">
          <el-input-number
            v-model="ratioForm.ratio"
            :min="0"
            :max="100"
            :precision="2"
            :step="0.01"
            :disabled="ratioForm.grade === 0"
            placeholder="请输入分润比例"
            style="width: 100%"
          />
          <div style="color: #999; font-size: 12px; margin-top: 5px">
            请输入0-100之间的数值，支持两位小数
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelRatio">取 消</el-button>
          <el-button type="primary" @click="submitRatio">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 账单对话框 -->
    <el-dialog
      :title="billTitle"
      v-model="billOpen"
      width="90%"
      :max-width="1200"
      append-to-body
      class="bill-dialog"
    >
      <el-form
        :model="billQueryParams"
        ref="billQueryRef"
        :inline="true"
        v-show="billShowSearch"
      >
        <div
          v-if="billQueryParams.agentName"
          style="
            margin-bottom: 15px;
            padding: 10px;
            background-color: #f0f9ff;
            border: 1px solid #b3d8ff;
            border-radius: 4px;
          "
        >
          <el-icon style="color: #409eff; margin-right: 5px"
            ><InfoFilled
          /></el-icon>
          <span style="color: #409eff; font-weight: 500"
            >当前查看：{{ billQueryParams.agentName }} 的账单记录</span
          >
          <span style="margin-left: 15px; color: #67c23a"
            >共 {{ billTotal }} 条记录</span
          >
        </div>
        <el-form-item label="代理服务商" prop="agentName">
          <el-input
            v-model="billQueryParams.agentName"
            placeholder="请输入代理服务商名称"
            clearable
            disabled
            @keyup.enter="handleBillQuery"
          />
        </el-form-item>
        <el-form-item label="订单号" prop="orderNum">
          <el-input
            v-model="billQueryParams.orderNum"
            placeholder="请输入订单号"
            clearable
            @keyup.enter="handleBillQuery"
          />
        </el-form-item>
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="billQueryParams.amount"
            placeholder="请输入金额"
            clearable
            @keyup.enter="handleBillQuery"
          />
        </el-form-item>
        <el-form-item label="变动前金额" prop="beforeAmount">
          <el-input
            v-model="billQueryParams.beforeAmount"
            placeholder="请输入变动前金额"
            clearable
            @keyup.enter="handleBillQuery"
          />
        </el-form-item>
        <el-form-item label="变动后金额" prop="afterAmount">
          <el-input
            v-model="billQueryParams.afterAmount"
            placeholder="请输入变动后金额"
            clearable
            @keyup.enter="handleBillQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleBillQuery"
            >搜索</el-button
          >
          <el-button icon="Refresh" @click="resetBillQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="billLoading"
        :data="billList"
        @selection-change="handleBillSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="MAC"
          align="center"
          prop="agentName"
          v-if="billColumns[0].visible"
        >
          <template #default="scope">
            <span class="agent-name-cell">{{ scope.row.sn || "-" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="订单号"
          align="center"
          prop="orderNum"
          v-if="billColumns[1].visible"
        />
        <el-table-column
          label="金额"
          align="center"
          prop="amount"
          v-if="billColumns[2].visible"
        >
          <template #default="scope">
            <span class="amount-cell amount-positive"
              >¥{{ scope.row.amount || "0.00" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="变动前金额"
          align="center"
          prop="beforeAmount"
          v-if="billColumns[3].visible"
        >
          <template #default="scope">
            <span class="amount-cell amount-neutral"
              >¥{{ scope.row.beforeAmount || "0.00" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="变动后金额"
          align="center"
          prop="afterAmount"
          v-if="billColumns[4].visible"
        >
          <template #default="scope">
            <span class="amount-cell amount-positive"
              >¥{{ scope.row.afterAmount || "0.00" }}</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="收益类型"
          align="center"
          prop="incomeType"
          v-if="billColumns[5].visible"
        />
        <el-table-column
          label="变动类型(增加，减少)"
          align="center"
          prop="changeType"
          v-if="billColumns[6].visible"
        />
        <el-table-column
          label="备注"
          align="center"
          prop="remark"
          v-if="billColumns[7].visible"
        />
      </el-table>

      <pagination
        v-show="billTotal > 0"
        :total="billTotal"
        v-model:page="billQueryParams.pageNum"
        v-model:limit="billQueryParams.pageSize"
        @pagination="getBillList"
      />

      <!-- 添加或修改账户订单对话框 -->
      <el-dialog
        :title="billDialogTitle"
        v-model="billDialogOpen"
        :width="billDialogWidth"
        append-to-body
      >
        <el-form ref="billFormRef" :model="billForm" :rules="billRules">
          <el-row :gutter="20">
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="代理服务商" prop="agentName">
                <el-input
                  v-model="billForm.agentName"
                  placeholder="请输入代理服务商名称"
                  :disabled="!!billQueryParams.agentName"
                />
              </el-form-item>
            </el-col>
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="订单号" prop="orderNum">
                <el-input
                  v-model="billForm.orderNum"
                  placeholder="请输入订单号"
                />
              </el-form-item>
            </el-col>
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="金额" prop="amount">
                <el-input v-model="billForm.amount" placeholder="请输入金额" />
              </el-form-item>
            </el-col>
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="变动前金额" prop="beforeAmount">
                <el-input
                  v-model="billForm.beforeAmount"
                  placeholder="请输入变动前金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="变动后金额" prop="afterAmount">
                <el-input
                  v-model="billForm.afterAmount"
                  placeholder="请输入变动后金额"
                />
              </el-form-item>
            </el-col>
            <el-col :span="isBillTwoColumnForm ? 12 : 24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="billForm.remark"
                  type="textarea"
                  placeholder="请输入内容"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitBillForm">确 定</el-button>
            <el-button @click="cancelBillDialog">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeBillDialog" type="primary">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 代理商详情对话框 -->
    <el-dialog
      :title="detailTitle"
      v-model="detailOpen"
      width="1000px"
      append-to-body
    >
      <el-tabs v-model="detailActiveTab" type="border-card">
        <!-- 基本信息标签页 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-descriptions :column="3" border size="small">
            <el-descriptions-item label="服务商名称" :span="1">
              <span class="detail-value">{{
                detailForm.agentName || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="用户名" :span="1">
              <span class="detail-value">{{ detailForm.userName || "-" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="代理商等级" :span="1">
              <dict-tag :options="agent_grade" :value="detailForm.grade" />
            </el-descriptions-item>
            <el-descriptions-item label="代理商层级" :span="1">
              <span class="detail-value">{{ detailForm.level || "-" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="团队机器总数" :span="1">
              <span class="detail-value">{{
                detailForm.machineNumber || "0"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="团队激活总数" :span="1">
              <span class="detail-value">{{
                detailForm.activeNumber || "0"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="实名状态" :span="1">
              <dict-tag
                :options="is_real_name"
                :value="detailForm.isRealName"
              />
            </el-descriptions-item>
            <el-descriptions-item label="等级到期时间" :span="1">
              <span class="detail-value">{{
                parseTime(detailForm.expireTime, "{y}-{m}-{d}") || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="分润钱包" :span="1">
              <span class="detail-value">{{ detailForm.wallet || "0" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="服务商状态" :span="1">
              <dict-tag :options="agent_status" :value="detailForm.status" />
            </el-descriptions-item>
            <el-descriptions-item label="上级代理商" :span="1">
              <span class="detail-value">{{
                detailForm.parentName || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="分润比例" :span="1">
              <span class="detail-value highlight"
                >{{ detailForm.ratio || "0" }}%</span
              >
            </el-descriptions-item>
            <el-descriptions-item label="邀请码" :span="1">
              <span class="detail-value">{{
                detailForm.invitationCode || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="是否允许处理商城订单发货" :span="1">
              <dict-tag :options="sys_yes_no" :value="detailForm.isOrder" />
            </el-descriptions-item>
            <el-descriptions-item label="创建时间" :span="1">
              <span class="detail-value">{{
                parseTime(detailForm.createTime, "{y}-{m}-{d} {h}:{i}:{s}") ||
                "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="更新时间" :span="1">
              <span class="detail-value">{{
                parseTime(detailForm.updateTime, "{y}-{m}-{d} {h}:{i}:{s}") ||
                "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="创建者" :span="1">
              <span class="detail-value">{{ detailForm.createBy || "-" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="更新者" :span="1">
              <span class="detail-value">{{ detailForm.updateBy || "-" }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="3">
              <span class="detail-value">{{ detailForm.remark || "-" }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-tab-pane>

        <!-- 联系信息标签页 -->
        <el-tab-pane label="联系信息" name="contact">
          <el-descriptions :column="2" border size="small">
            <el-descriptions-item label="联系人电话">
              <span class="detail-value">{{
                detailForm.contactPhone || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="联系人姓名">
              <span class="detail-value">{{
                detailForm.contactName || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="联系人邮箱">
              <span class="detail-value">{{
                detailForm.contactEmail || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="邮寄地址">
              <span class="detail-value">{{
                detailForm.contactAddress || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              <span class="detail-value">{{
                detailForm.cardNumber || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="证件开始时间">
              <span class="detail-value">{{
                parseTime(detailForm.startTime, "{y}-{m}-{d}") || "-"
              }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="证件到期时间" :span="2">
              <span class="detail-value">{{
                parseTime(detailForm.endTime, "{y}-{m}-{d}") || "-"
              }}</span>
            </el-descriptions-item>
          </el-descriptions>

          <!-- 身份证照片展示 -->
          <div style="margin-top: 20px">
            <h4 style="margin-bottom: 15px; color: #409eff">身份证照片</h4>
            <el-row :gutter="20">
              <el-col :span="12">
                <div v-if="detailForm.cardFrontUrl" class="id-card-container">
                  <p class="id-card-title">身份证正面照片：</p>
                  <el-image
                    :src="detailForm.cardFrontUrl"
                    class="id-card-image"
                    :preview-src-list="[detailForm.cardFrontUrl]"
                    fit="cover"
                  />
                </div>
                <div v-else class="no-image">
                  <el-empty description="暂无正面照片" :image-size="60" />
                </div>
              </el-col>
              <el-col :span="12">
                <div v-if="detailForm.cardBackUrl" class="id-card-container">
                  <p class="id-card-title">身份证反面照片：</p>
                  <el-image
                    :src="detailForm.cardBackUrl"
                    class="id-card-image"
                    :preview-src-list="[detailForm.cardBackUrl]"
                    fit="cover"
                  />
                </div>
                <div v-else class="no-image">
                  <el-empty description="暂无反面照片" :image-size="60" />
                </div>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 银行卡信息标签页 -->
        <el-tab-pane label="银行卡信息" name="bank">
          <div v-if="detailForm.list && detailForm.list.length > 0">
            <el-table
              :data="detailForm.list"
              border
              style="width: 100%"
              size="small"
              stripe
            >
              <el-table-column prop="name" label="户名" width="100" />
              <el-table-column
                prop="accountNumber"
                label="银行卡号"
                width="180"
                show-overflow-tooltip
              />
              <el-table-column
                prop="withdrawalType"
                label="提现类型"
                width="100"
                align="center"
              >
                <template #default="scope">
                  <el-tag
                    :type="
                      scope.row.withdrawalType === 1 ? 'primary' : 'success'
                    "
                    size="small"
                  >
                    {{ scope.row.withdrawalType === 1 ? "个人" : "对公" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="openingBankName"
                label="开户行"
                width="120"
                show-overflow-tooltip
              />
              <el-table-column
                prop="bankAddress"
                label="开户地址"
                width="150"
                show-overflow-tooltip
              />
              <el-table-column
                prop="provinceName"
                label="开户行省"
                width="80"
              />
              <el-table-column prop="cityName" label="开户行市" width="80" />
              <el-table-column
                prop="districtName"
                label="开户行区"
                width="80"
              />
              <el-table-column
                prop="phoneNumber"
                label="银行预留手机号"
                width="120"
              />
              <el-table-column
                prop="isDefault"
                label="是否默认"
                width="80"
                align="center"
              >
                <template #default="scope">
                  <el-tag
                    :type="scope.row.isDefault === 1 ? 'success' : 'info'"
                    size="small"
                  >
                    {{ scope.row.isDefault === 1 ? "是" : "否" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="remark"
                label="备注"
                width="100"
                show-overflow-tooltip
              />
            </el-table>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无银行卡信息" :image-size="80" />
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false" type="primary"
            >关 闭</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Agent">
import {
  listAgent,
  getAgent,
  delAgent,
  addAgent,
  updateAgent,
  bankList,
  branchList,
  districtList as getDistrictList,
  addBankCard,
  addRatio,
  getAgentInfo,
  resetPassword,
  updateProviderId,
} from "@/api/agent/agent";
import {
  listBill,
  getBill,
  delBill,
  addBill,
  updateBill,
} from "@/api/agent/bill";
import {
  ref,
  onMounted,
  watch,
  computed,
  reactive,
  toRefs,
  getCurrentInstance,
} from "vue";
import { upload } from "@/api/portal/banner";
import auth from "@/plugins/auth.js";
import { listPlugin } from "@/api/deviceBox/plugin";
const hasPermi = auth.hasPermi;
const { proxy } = getCurrentInstance();
const {
  bank_name,
  sys_yes_no,
  account_type,
  agent_grade,
  is_real_name,
  agent_status,
} = proxy.useDict(
  "bank_name",
  "sys_yes_no",
  "account_type",
  "agent_grade",
  "is_real_name",
  "agent_status"
);

const agentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const modifyData = ref("contactName");

// 添加银行列表数据
const bankListData = ref([]);
const bankLoading = ref(false);

// 添加省市区三级联动数据
const provinceList = ref([]);
const cityList = ref([]);
const districtList = ref([]);

// 添加省市区loading状态
const districtLoading = ref(false);
const cityLoading = ref(false);
const districtDetailLoading = ref(false);

// 身份证照片上传相关
const cardFrontFileList = ref([]);
const cardBackFileList = ref([]);
const cardFrontUploadRef = ref(null);
const cardBackUploadRef = ref(null);
const dialogVisible = ref(false);
const dialogImageUrl = ref("");

// 银行卡相关
const bankCardOpen = ref(false);
const bankCardTitle = ref("新增银行卡");
const bankCardForm = ref({
  name: "",
  accountNumber: "",
  withdrawalType: 1,
  provinceCode: "",
  provinceName: "",
  cityCode: "",
  cityName: "",
  districtCode: "",
  districtName: "",
  isDefault: 1,
  openingBank: "",
  openingBankName: "",
  provinceBranchName: "",
});

const bankCardRules = {
  name: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  accountNumber: [
    { required: true, message: "银行卡号不能为空", trigger: "blur" },
  ],
  openingBankName: [
    { required: true, message: "开户行不能为空", trigger: "change" },
  ],
  provinceBranchName: [
    { required: true, message: "开户支行不能为空", trigger: "blur" },
  ],
  provinceName: [
    { required: true, message: "开户行省不能为空", trigger: "change" },
  ],
  cityName: [
    { required: true, message: "开户行市不能为空", trigger: "change" },
  ],
  districtName: [
    { required: true, message: "开户行区不能为空", trigger: "change" },
  ],
};

// 分润比例相关
const ratioOpen = ref(false);
const ratioTitle = ref("配置分润比例");
const ratioForm = ref({
  id: null,
  agentName: "",
  ratio: 0,
  grade: 1,
});

const ratioRules = {
  ratio: [
    { required: true, message: "分润比例不能为空", trigger: "blur" },
    {
      type: "number",
      min: 0,
      max: 100,
      message: "分润比例必须在0-100之间",
      trigger: "blur",
    },
  ],
};
const ysList = ref([
  {
    cloudName: "无",
    providerId: "",
  },
]);
function getYsList() {
  listPlugin({ hasPage: false }).then((response) => {
    console.log(response);
    response.rows.forEach((item) => {
      ysList.value.push({
        cloudName: item.cloudName,
        providerId: item.providerId,
      });
    });
  });
}
getYsList();

function ySChange (row){
  updateProviderId(row.id, row.providerId).then(response => {
    if(response.code === 200){
      proxy.$modal.msgSuccess("修改云商ID成功");
      getList();
    } else {
      proxy.$modal.msgError("修改云商ID失败");
    }
  }).catch(error => {
    proxy.$modal.msgError("修改云商ID失败");
  });
}

// 列显隐信息
const columns = ref([
  { key: 0, label: `服务商名称`, visible: true },
  { key: 1, label: `用户名`, visible: true },
  { key: 2, label: `代理商等级`, visible: true },
  { key: 3, label: `代理商层级`, visible: true },
  { key: 4, label: `团队机器总数`, visible: true },
  { key: 5, label: `团队激活总数`, visible: true },
  { key: 6, label: `实名状态`, visible: true },
  { key: 7, label: `等级到期时间`, visible: true },
  { key: 8, label: `分润钱包`, visible: true },
  { key: 9, label: `服务商状态`, visible: true },
  { key: 10, label: `上级代理商ID`, visible: true },
  { key: 11, label: `云商名称`, visible: true },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    agentName: null,
    isRealName: null,
    status: null,
    parentName: null,
    userName:null
  },
  rules: {
    agentName: [
      { required: true, message: "服务商名称不能为空", trigger: "blur" },
    ],
    contactPhone: [
      { required: true, message: "服务商电话不能为空", trigger: "blur" },
    ],
    password: [
      { required: true, message: "服务商密码不能为空", trigger: "blur" },
    ],
    contactName: [
      { required: true, message: "服务商姓名不能为空", trigger: "blur" },
    ],
    cardNumber: [
      { required: true, message: "身份证号不能为空", trigger: "blur" },
    ],
    cardIssueDate: [
      { required: true, message: "发证时间不能为空", trigger: "change" },
    ],
    cardExpireDate: [
      { required: true, message: "证件到期时间不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const tabs = ref([
  { name: "basic", label: "基本信息" },
  { name: "settle", label: "结算信息" },
  { name: "realname", label: "实名认证" },
  { name: "confirm", label: "配置" },
]);

// const activeTab = ref('basic')
const activeTab = ref(tabs.value[0].name);
const tabOrder = ["basic", "settle", "realname", "confirm"];
const numData = ref(0);
const TabData = ref(["contactName", "settle", "realname", "confirm"]);
const prevTab = () => {
  if (numData.value > 0) {
    numData.value = numData.value - 1;
    modifyData.value = TabData.value[numData.value];
  }
};

const nextTab = async () => {
  try {
    // 添加表单验证
    await proxy.$refs["agentRef"].validate();

    if (numData.value < TabData.value.length - 1) {
      numData.value = numData.value + 1;
      modifyData.value = TabData.value[numData.value];
    }
  } catch (error) {
    proxy.$modal.msgError("请先完成当前Tab的必填项");
  }
};

/** 查询代理商信息列表 */
function getList() {
  loading.value = true;
  listAgent(queryParams.value).then((response) => {
    agentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
  // 清空上传组件
  if (cardFrontUploadRef.value) {
    cardFrontUploadRef.value.clearFiles();
  }
  if (cardBackUploadRef.value) {
    cardBackUploadRef.value.clearFiles();
  }
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    agentName: null,
    contactName: null,
    contactPhone: null,
    contactEmail: null,
    contactAddress: null,
    isOrder: null,
    cardNumber: null,
    cardFrontUrl: null,
    cardBackUrl: null,
    cardIssueDate: null,
    cardExpireDate: null,
    holdingCardUrl: null,
    bankPhotoUrl: null,
    accountType: 1,
    bankName: null,
    openingBank: null,
    bankAddress: null,
    bankAccount: null,
    phoneNumber: null,
    province: null,
    city: null,
    district: null,
    password: null,
  };

  // 重置Tab状态
  numData.value = 0;
  modifyData.value = TabData.value[0];

  // 清空联动数据
  cityList.value = [];
  districtList.value = [];

  // 清空身份证照片文件列表
  cardFrontFileList.value = [];
  cardBackFileList.value = [];

  proxy.resetForm("agentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}
const idss = ref([]);
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  idss.value = selection.map((item) => item.agentName);
  single.value = selection.length !== 1;
  multiple.value = selection.length === 0;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加代理商信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  modifyData.value = "contactName";
  reset();

  // 调用getAgentInfo接口获取详细信息
  getAgentInfo(row.id)
    .then(async (response) => {
      if (response.code === 200) {
        const agentInfo = response.data;
        // 查找isDefault为1的银行卡对象
        let defaultBankCard = null;
        if (agentInfo.list && Array.isArray(agentInfo.list)) {
          defaultBankCard = agentInfo.list.find((card) => card.isDefault === 1);
        }
        // 设置基本信息
        form.value = {
          id: agentInfo.id,
          agentName: agentInfo.agentName,
          contactName: agentInfo.contactName,
          contactPhone: agentInfo.contactPhone,
          contactEmail: agentInfo.contactEmail,
          contactAddress: agentInfo.contactAddress,
          isOrder: agentInfo.isOrder,
          cardNumber: agentInfo.cardNumber,
          cardFrontUrl: agentInfo.cardFrontUrl,
          cardBackUrl: agentInfo.cardBackUrl,
          cardIssueDate: agentInfo.startTime, // 发证时间
          cardExpireDate: agentInfo.endTime, // 证件到期时间
          holdingCardUrl: agentInfo.holdingCardUrl,
          bankPhotoUrl: agentInfo.bankPhotoUrl,
          accountType: agentInfo.accountType || 1,
          bankName: defaultBankCard
            ? defaultBankCard.openingBankName
            : agentInfo.openingBankName,
          bankAddress: agentInfo.bankAddress,
          bankAccount: defaultBankCard
            ? defaultBankCard.accountNumber
            : agentInfo.accountNumber,
          phoneNumber: agentInfo.phoneNumber,
          province: defaultBankCard
            ? defaultBankCard.provinceName
            : agentInfo.provinceName,
          city: defaultBankCard ? defaultBankCard.cityName : agentInfo.cityName,
          district: defaultBankCard
            ? defaultBankCard.districtName
            : agentInfo.districtName,
          password: agentInfo.password,
          provinceBranchName: defaultBankCard
            ? defaultBankCard.provinceBranchName
            : agentInfo.provinceBranchName,
        };
        // 自动回显省市区联动
        if (form.value.province) {
          await loadDistrictList();
          await handleProvinceChange(form.value.province);
          if (form.value.city) {
            await handleCityChange(form.value.city);
          }
        }
        // 先加载银行列表，然后加载支行列表
        if (form.value.bankName) {
          loadBankList().then(() => {
            // 银行列表加载完成后，加载支行列表
            let selectedBank = bankListData.value.find(
              (bank) => bank.name === form.value.bankName
            );
            // 如果精确匹配失败，尝试模糊匹配
            if (!selectedBank) {
              selectedBank = bankListData.value.find(
                (bank) =>
                  bank.name.includes(form.value.bankName) ||
                  form.value.bankName.includes(bank.name)
              );
            }
            if (selectedBank) {
              loadBranchList(selectedBank.id);
            }
          });
        }

        // 如果有身份证照片，设置文件列表
        if (form.value.cardFrontUrl) {
          cardFrontFileList.value = [
            { url: form.value.cardFrontUrl, uid: Date.now() },
          ];
        }
        if (form.value.cardBackUrl) {
          cardBackFileList.value = [
            { url: form.value.cardBackUrl, uid: Date.now() + 1 },
          ];
        }

        open.value = true;
        title.value = "修改代理商信息";
      } else {
        proxy.$modal.msgError("获取代理商信息失败");
      }
    })
    .catch((error) => {
      proxy.$modal.msgError("获取代理商信息失败");
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.agentName || idss.value;
  proxy.$modal
    .confirm('是否确认删除代理商信息编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delAgent(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "agent/agent/export",
    {
      ...queryParams.value,
    },
    `agent_${new Date().getTime()}.xlsx`
  );
}

// 获取银行列表
const loadBankList = async () => {
  bankLoading.value = true;
  try {
    const response = await bankList({ hasPage: true });

    if (response.code === 200) {
      bankListData.value = response.data || response.rows || [];
    } else {
      bankListData.value = [];
    }
  } catch (err) {
    bankListData.value = [];
  } finally {
    bankLoading.value = false;
  }
};

// 获取地区列表
const loadDistrictList = async () => {
  districtLoading.value = true;
  try {
    // 获取省份列表（level=1，不需要pcode）
    const response = await getDistrictList({ level: 1 });
    if (response.code === 200) {
      provinceList.value = response.data || response.rows || [];
    } else {
      provinceList.value = [];
    }
  } catch (err) {
    provinceList.value = [];
  } finally {
    districtLoading.value = false;
  }
};

// 处理省份选择变化
const handleProvinceChange = async (provinceName) => {
  form.value.city = "";
  form.value.district = "";
  cityList.value = [];
  districtList.value = [];

  if (provinceName) {
    const selectedProvince = provinceList.value.find(
      (province) => province.name === provinceName
    );
    if (selectedProvince) {
      // 根据省份code获取城市列表（level=2，pcode=省份code）
      cityLoading.value = true;
      try {
        const response = await getDistrictList({
          level: 2,
          pcode: selectedProvince.code,
        });
        if (response.code === 200) {
          cityList.value = response.data || response.rows || [];
        } else {
          cityList.value = [];
        }
      } catch (err) {
        cityList.value = [];
      } finally {
        cityLoading.value = false;
      }
    }
  }
};

// 处理城市选择变化
const handleCityChange = async (cityName) => {
  form.value.district = "";
  districtList.value = [];

  if (cityName) {
    const selectedCity = cityList.value.find((city) => city.name === cityName);
    if (selectedCity) {
      // 根据城市code获取区县列表（level=3，pcode=城市code）
      districtDetailLoading.value = true;
      try {
        const response = await getDistrictList({
          level: 3,
          pcode: selectedCity.code,
        });
        if (response.code === 200) {
          districtList.value = response.data || response.rows || [];
        } else {
          districtList.value = [];
        }
      } catch (err) {
        districtList.value = [];
      } finally {
        districtDetailLoading.value = false;
      }
    }
  }
};

// 监听银行选择变化
watch(
  () => form.value.bankName,
  (newBankName, oldBankName) => {
    if (newBankName) {
      // 根据银行名称找到对应的银行ID
      const selectedBank = bankListData.value.find(
        (bank) => bank.name === newBankName
      );

      if (selectedBank) {
        // 清空支行选择
        form.value.openingBank = "";
      } else {
        // 清空支行列表和选择
        form.value.openingBank = "";
      }
    } else {
      // 清空支行列表和选择
      form.value.openingBank = "";
    }
  },
  { immediate: true }
); // 添加immediate选项，确保初始化时也能触发

// 在页面加载时获取银行列表
onMounted(() => {
  loadBankList();
  loadDistrictList();

  // 统计账单表单字段数量
  billFieldCount.value = [
    "agentName",
    "orderNum",
    "amount",
    "beforeAmount",
    "afterAmount",
    "incomeType",
    "changeType",
    "remark",
  ].length;
});

/** 添加银行卡按钮操作 */
function handleAddBankCard(row) {
  // 重置银行卡表单
  resetBankCardForm();

  // 设置当前代理商信息
  bankCardForm.value.name = row.agentName || row.contactName || "";

  // 打开银行卡对话框
  bankCardOpen.value = true;
  bankCardTitle.value = "新增银行卡";

  // 加载银行和地区列表
  loadBankList();
  loadDistrictList();
}

// 处理银行选择变化
const handleBankChange = (bankName) => {
  if (bankName) {
    const selectedBank = bankListData.value.find(
      (bank) => bank.name === bankName
    );
    if (selectedBank) {
      // 清空支行选择
      form.value.openingBank = "";
    }
  }
  form.value.openingBank = "";
};

// 身份证正面照片上传处理
const handleCardFrontChange = (file) => {
  let formData = new FormData();
  formData.append("file", file.raw);
  upload(formData)
    .then((response) => {
      if (response.code === 200) {
        const imageUrl = `https://huadunyun-cdn.oss-cn-beijing.aliyuncs.com${response.imgUrl}`;
        cardFrontFileList.value = [{ url: imageUrl, uid: file.uid }];
        form.value.cardFrontUrl = imageUrl;
        proxy.$modal.msgSuccess("身份证正面照片上传成功");
      } else {
        proxy.$modal.msgError(response.msg || "上传失败");
      }
    })
    .catch((error) => {
      proxy.$modal.msgError("上传失败");
    });
};

// 身份证反面照片上传处理
const handleCardBackChange = (file) => {
  let formData = new FormData();
  formData.append("file", file.raw);
  upload(formData)
    .then((response) => {
      if (response.code === 200) {
        const imageUrl = `https://huadunyun-cdn.oss-cn-beijing.aliyuncs.com${response.imgUrl}`;
        cardBackFileList.value = [{ url: imageUrl, uid: file.uid }];
        form.value.cardBackUrl = imageUrl;
        proxy.$modal.msgSuccess("身份证反面照片上传成功");
      } else {
        proxy.$modal.msgError(response.msg || "上传失败");
      }
    })
    .catch((error) => {
      proxy.$modal.msgError("上传失败");
    });
};

// 身份证正面照片删除处理
const handleCardFrontRemove = (file) => {
  cardFrontFileList.value = [];
  form.value.cardFrontUrl = "";
  proxy.$modal.msgSuccess("删除成功");
};

// 身份证反面照片删除处理
const handleCardBackRemove = (file) => {
  cardBackFileList.value = [];
  form.value.cardBackUrl = "";
  proxy.$modal.msgSuccess("删除成功");
};

// 图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};

// 银行卡表单相关函数
const resetBankCardForm = () => {
  bankCardForm.value = {
    name: "",
    accountNumber: "",
    withdrawalType: 1,
    provinceCode: "",
    provinceName: "",
    cityCode: "",
    cityName: "",
    districtCode: "",
    districtName: "",
    isDefault: 1,
    openingBank: "",
    openingBankName: "",
    provinceBranchName: "",
  };

  // 清空联动数据
  cityList.value = [];
  districtList.value = [];

  proxy.resetForm("bankCardRef");
};

const cancelBankCard = () => {
  bankCardOpen.value = false;
  resetBankCardForm();
};

const submitBankCard = () => {
  proxy.$refs["bankCardRef"].validate((valid) => {
    if (valid) {
      // 获取对应的ID和代码
      const selectedBank = bankListData.value.find(
        (bank) => bank.name === bankCardForm.value.openingBankName
      );
      const selectedProvince = provinceList.value.find(
        (province) => province.name === bankCardForm.value.provinceName
      );
      const selectedCity = cityList.value.find(
        (city) => city.name === bankCardForm.value.cityName
      );
      const selectedDistrict = districtList.value.find(
        (district) => district.name === bankCardForm.value.districtName
      );
      // 构建API数据
      const apiData = {
        name: bankCardForm.value.name,
        accountNumber: bankCardForm.value.accountNumber,
        withdrawalType: bankCardForm.value.withdrawalType,
        provinceCode: selectedProvince
          ? selectedProvince.code
          : bankCardForm.value.provinceName,
        provinceName: bankCardForm.value.provinceName,
        cityCode: selectedCity
          ? selectedCity.code
          : bankCardForm.value.cityName,
        cityName: bankCardForm.value.cityName,
        districtCode: selectedDistrict
          ? selectedDistrict.code
          : bankCardForm.value.districtName,
        districtName: bankCardForm.value.districtName,
        isDefault: bankCardForm.value.isDefault,
        openingBank: selectedBank
          ? selectedBank.id
          : bankCardForm.value.openingBankName,
        openingBankName: bankCardForm.value.openingBankName,
        provinceBranchName: bankCardForm.value.provinceBranchName,
      };
      // 调用新增银行卡接口
      addBankCard(apiData)
        .then((response) => {
          proxy.$modal.msgSuccess("新增银行卡成功");
          bankCardOpen.value = false;
          resetBankCardForm();
        })
        .catch((error) => {
          proxy.$modal.msgError("新增银行卡失败");
        });
    }
  });
};

// 银行卡表单的省份选择变化处理
const handleBankCardProvinceChange = async (provinceName) => {
  bankCardForm.value.cityName = "";
  bankCardForm.value.districtName = "";
  cityList.value = [];
  districtList.value = [];

  if (provinceName) {
    const selectedProvince = provinceList.value.find(
      (province) => province.name === provinceName
    );
    if (selectedProvince) {
      cityLoading.value = true;
      try {
        const response = await getDistrictList({
          level: 2,
          pcode: selectedProvince.code,
        });
        if (response.code === 200) {
          cityList.value = response.data || response.rows || [];
        } else {
          cityList.value = [];
        }
      } catch (err) {
        cityList.value = [];
      } finally {
        cityLoading.value = false;
      }
    }
  }
};

// 银行卡表单的城市选择变化处理
const handleBankCardCityChange = async (cityName) => {
  bankCardForm.value.districtName = "";
  districtList.value = [];

  if (cityName) {
    const selectedCity = cityList.value.find((city) => city.name === cityName);
    if (selectedCity) {
      districtDetailLoading.value = true;
      try {
        const response = await getDistrictList({
          level: 3,
          pcode: selectedCity.code,
        });
        if (response.code === 200) {
          districtList.value = response.data || response.rows || [];
        } else {
          districtList.value = [];
        }
      } catch (err) {
        districtList.value = [];
      } finally {
        districtDetailLoading.value = false;
      }
    }
  }
};

// 分润比例相关函数
const handleConfigRatio = (row) => {
  // 重置分润比例表单
  resetRatioForm();

  // 设置当前代理商信息
  ratioForm.value.id = row.id;
  ratioForm.value.agentName = row.agentName || "";
  ratioForm.value.ratio = row.ratio || 0;
  ratioForm.value.grade = row.grade || 0;

  // 打开分润比例对话框
  ratioOpen.value = true;
  ratioTitle.value = "配置分润比例";
};

const resetRatioForm = () => {
  ratioForm.value = {
    id: null,
    agentName: "",
    ratio: 0,
    grade: 1,
  };
  proxy.resetForm("ratioRef");
};

const cancelRatio = () => {
  ratioOpen.value = false;
  resetRatioForm();
};

const submitRatio = () => {
  proxy.$refs["ratioRef"].validate((valid) => {
    if (valid) {
      // 构建API数据
      const apiData = {
        id: ratioForm.value.id,
        ratio: ratioForm.value.ratio,
      };

      // 调用配置分润比例接口
      addRatio(apiData)
        .then((response) => {
          proxy.$modal.msgSuccess("配置分润比例成功");
          ratioOpen.value = false;
          resetRatioForm();
          // 刷新列表
          getList();
        })
        .catch((error) => {
          proxy.$modal.msgError("配置分润比例失败");
        });
    }
  });
};

// 代理商详情对话框
const detailOpen = ref(false);
const detailTitle = ref("代理商详情");
const detailForm = ref({});
const detailActiveTab = ref("basic");

// 账单相关变量
const billOpen = ref(false);
const billTitle = ref("账单管理");
const billLoading = ref(true);
const billShowSearch = ref(true);
const billIds = ref([]);
const billSingle = ref(true);
const billMultiple = ref(true);
const billTotal = ref(0);
const billList = ref([]);
const billDialogOpen = ref(false);
const billDialogTitle = ref("");
const billForm = ref({});
const billQueryParams = ref({
  pageNum: 1,
  pageSize: 10,
  agentName: null,
  orderNum: null,
  amount: null,
  beforeAmount: null,
  afterAmount: null,
  incomeType: null,
  changeType: null,
});

// 账单列显隐信息
const billColumns = ref([
  { key: 0, label: `代理服务商`, visible: true },
  { key: 1, label: `订单号`, visible: true },
  { key: 2, label: `金额`, visible: true },
  { key: 3, label: `变动前金额`, visible: true },
  { key: 4, label: `变动后金额`, visible: true },
  { key: 5, label: `收益类型`, visible: true },
  { key: 6, label: `变动类型(增加，减少)`, visible: true },
  { key: 7, label: `备注`, visible: true },
]);

// 账单表单验证规则
const billRules = {
  agentName: [
    { required: true, message: "代理服务商不能为空", trigger: "blur" },
  ],
  orderNum: [{ required: true, message: "订单号不能为空", trigger: "blur" }],
  amount: [{ required: true, message: "金额不能为空", trigger: "blur" }],
  beforeAmount: [
    { required: true, message: "变动前金额不能为空", trigger: "blur" },
  ],
  afterAmount: [
    { required: true, message: "变动后金额不能为空", trigger: "blur" },
  ],
};

// 账单表单字段数量计算
const billFieldCount = ref(0);
const isBillTwoColumnForm = computed(() => billFieldCount.value > 8);
const billDialogWidth = computed(() =>
  isBillTwoColumnForm.value ? "60vw" : "500px"
);

function handleViewDetail(row) {
  reset();
  // 重置标签页为基本信息
  detailActiveTab.value = "basic";
  // 调用API获取详细信息
  getAgentInfo(row.id)
    .then((response) => {
      if (response.code === 200) {
        detailForm.value = response.data;
        detailOpen.value = true;
        detailTitle.value = "代理商详情";
      } else {
        proxy.$modal.msgError("获取代理商详情失败");
      }
    })
    .catch((error) => {
      proxy.$modal.msgError("获取代理商详情失败");
    });
}

/** 重置密码按钮操作 */
function handleResetPassword(row) {
  proxy.$modal
    .confirm('是否确认重置代理商"' + row.agentName + '"的密码？')
    .then(function () {
      return resetPassword(row.userName);
    })
    .then((response) => {
      // 接口返回成功后再显示提示信息
      if (response && response.code === 200) {
        proxy.$modal.msgSuccess("重置密码成功");
        getList();
      } else {
        proxy.$modal.msgError("重置密码失败");
      }
    })
    .catch(() => {
      // proxy.$modal.msgError("重置密码失败");
    });
}

/** 查看账单按钮操作 */
function handleViewBill(row) {
  billOpen.value = true;
  const agentName = row.agentName || row.userName || "代理商";
  billTitle.value = `${agentName} - 账单管理`;
  // 设置代理服务商名称为当前代理商名称，用于筛选该代理商的账单
  billQueryParams.value.agentName = agentName;
  // 重置查询参数
  billQueryParams.value.pageNum = 1;
  billQueryParams.value.orderNum = null;
  billQueryParams.value.amount = null;
  billQueryParams.value.beforeAmount = null;
  billQueryParams.value.afterAmount = null;
  billQueryParams.value.incomeType = null;
  billQueryParams.value.changeType = null;
  // 显示加载状态
  billLoading.value = true;
  getBillList();
}

/** 查询账单列表 */
function getBillList() {
  billLoading.value = true;
  listBill(billQueryParams.value)
    .then((response) => {
      billList.value = response.rows;
      billTotal.value = response.total;
      billLoading.value = false;
    })
    .catch((error) => {
      proxy.$modal.msgError("获取账单列表失败");
      billLoading.value = false;
    });
}

/** 账单搜索按钮操作 */
function handleBillQuery() {
  billQueryParams.value.pageNum = 1;
  getBillList();
}

/** 账单重置按钮操作 */
function resetBillQuery() {
  proxy.resetForm("billQueryRef");
  // 保留当前代理服务商名称，不清空
  const currentAgentName = billQueryParams.value.agentName;
  billQueryParams.value = {
    pageNum: 1,
    pageSize: 10,
    agentName: currentAgentName,
    orderNum: null,
    amount: null,
    beforeAmount: null,
    afterAmount: null,
    incomeType: null,
    changeType: null,
  };
  handleBillQuery();
}

/** 账单多选框选中数据 */
function handleBillSelectionChange(selection) {
  billIds.value = selection.map((item) => item.id);
  billSingle.value = selection.length != 1;
  billMultiple.value = !selection.length;
}

/** 账单新增按钮操作 */
function handleBillAdd() {
  resetBillForm();
  // 自动填充当前代理服务商名称
  billForm.value.agentName = billQueryParams.value.agentName;
  billDialogOpen.value = true;
  billDialogTitle.value = "添加账户订单";
}

/** 账单修改按钮操作 */
function handleBillUpdate(row) {
  resetBillForm();
  const _id = row.id || billIds.value;
  getBill(_id)
    .then((response) => {
      billForm.value = response.data;
      billDialogOpen.value = true;
      billDialogTitle.value = "修改账户订单";
    })
    .catch((error) => {
      proxy.$modal.msgError("获取账单详情失败");
    });
}

/** 账单删除按钮操作 */
function handleBillDelete(row) {
  const _ids = row.id || billIds.value;
  proxy.$modal
    .confirm('是否确认删除账户订单编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delBill(_ids);
    })
    .then(() => {
      getBillList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch((error) => {
      proxy.$modal.msgError("删除失败");
    });
}

/** 账单导出按钮操作 */
function handleBillExport() {
  proxy
    .download(
      "agent/bill/export",
      {
        ...billQueryParams.value,
      },
      `bill_${new Date().getTime()}.xlsx`
    )
    .catch((error) => {
      proxy.$modal.msgError("导出失败");
    });
}

/** 账单表单重置 */
function resetBillForm() {
  billForm.value = {
    id: null,
    agentName: null,
    orderNum: null,
    amount: null,
    beforeAmount: null,
    afterAmount: null,
    incomeType: null,
    changeType: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("billFormRef");
}

/** 账单对话框取消按钮 */
function cancelBillDialog() {
  billDialogOpen.value = false;
  resetBillForm();
}

/** 账单表单提交按钮 */
function submitBillForm() {
  proxy.$refs["billFormRef"].validate((valid) => {
    if (valid) {
      if (billForm.value.id != null) {
        updateBill(billForm.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            billDialogOpen.value = false;
            getBillList();
          })
          .catch((error) => {
            proxy.$modal.msgError("修改失败");
          });
      } else {
        addBill(billForm.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            billDialogOpen.value = false;
            getBillList();
          })
          .catch((error) => {
            proxy.$modal.msgError("新增失败");
          });
      }
    }
  });
}

/** 关闭账单弹窗 */
function closeBillDialog() {
  billOpen.value = false;
  // 重置账单相关状态
  billList.value = [];
  billTotal.value = 0;
  billIds.value = [];
  billSingle.value = true;
  billMultiple.value = true;
  // 重置查询参数
  billQueryParams.value.agentName = null;
  // 关闭子对话框
  billDialogOpen.value = false;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["agentRef"].validate((valid) => {
    if (valid) {
      // 转换表单数据为API期望的格式
      const apiData = {
        withdrawalType: 1, // 提现类型，固定值
        provinceName: form.value.province, // 开户行省
        provinceCode: "", // 开户行省id，需要根据省份名称获取
        cityCode: "", // 开户行市id，需要根据城市名称获取
        cityName: form.value.city, // 开户行市
        districtCode: "", // 开户行区id，需要根据区县名称获取
        districtName: form.value.district, // 开户行区
        openingBank: "", // 开户行，需要根据银行名称获取
        openingBankName: form.value.bankName, // 开户行名称
        provinceBranchName: form.value.provinceBranchName, // 开户行支行名称
        accountNumber: form.value.bankAccount, // 银行卡号
        contactPhone: form.value.contactPhone, // 联系电话
        isDefault: 1, // 默认值
        contactName: form.value.contactName, // 联系人
        agentName: form.value.agentName, // 服务商名称
        password: form.value.password, // 密码
        ratio: 0, // 提现比例
        cardFrontUrl: form.value.cardFrontUrl, // 身份证图片
        cardBackUrl: form.value.cardBackUrl, // 身份证图片
        cardNumber: form.value.cardNumber, // 身份证号码
        startTime: form.value.cardIssueDate, // 开始时间
        endTime: form.value.cardExpireDate, // 结束时间
      };
      // 如果是修改操作，需要传递id
      if (form.value.id != null) {
        apiData.id = form.value.id;
      }
      // 如果有银行卡信息，需要获取对应的ID和代码
      if (form.value.bankAccount && form.value.bankName) {
        // 根据银行名称找到对应的银行ID
        const selectedBank = bankListData.value.find(
          (bank) => bank.name === form.value.bankName
        );
        // 根据省市区名称找到对应的code
        const selectedProvince = provinceList.value.find(
          (province) => province.name === form.value.province
        );
        const selectedCity = cityList.value.find(
          (city) => city.name === form.value.city
        );
        const selectedDistrict = districtList.value.find(
          (district) => district.name === form.value.district
        );
        // 更新ID和代码字段
        apiData.provinceCode = selectedProvince
          ? selectedProvince.code
          : form.value.province;
        apiData.cityCode = selectedCity ? selectedCity.code : form.value.city;
        apiData.districtCode = selectedDistrict
          ? selectedDistrict.code
          : form.value.district;
        apiData.openingBank = selectedBank
          ? selectedBank.id
          : form.value.bankName;
        apiData.openingBankName = form.value.bankName;
        apiData.provinceBranchName = form.value.provinceBranchName;
      }
      if (form.value.id != null) {
        updateAgent(apiData)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          })
          .catch((error) => {
            proxy.$modal.msgError("修改失败：" + (error.message || "未知错误"));
          });
      } else {
        addAgent(apiData)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          })
          .catch((error) => {
            proxy.$modal.msgError("新增失败：" + (error.message || "未知错误"));
          });
      }
    }
  });
}

getList();
</script>
<style>
.cell {
  display: flex;
  align-items: center;
  justify-content: center;
}
/* 增强选择器权重 */
body .el-dropdown .el-dropdown-selfdefine:hover,
body .el-dropdown__caret-button:hover {
  background-color: inherit !important;
  border-color: transparent !important;
  color: inherit !important;
}

/* 更精准的选择器 */
.el-dropdown > .el-dropdown-selfdefine:not(.is-disabled):hover,
.el-dropdown
  > .el-button-group
  > .el-dropdown__caret-button:not(.is-disabled):hover {
  background-color: inherit !important;
  border-color: transparent !important;
  color: inherit !important;
}

/* 账单弹窗样式 */
.bill-dialog .el-dialog__body {
  padding: 20px;
  max-height: 70vh;
  overflow-y: auto;
}

.bill-dialog .el-table {
  margin-top: 10px;
}

.bill-dialog .el-form--inline .el-form-item {
  margin-right: 10px;
  margin-bottom: 10px;
}

.bill-dialog .el-dialog__header {
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 15px;
}

.bill-dialog .el-dialog__footer {
  border-top: 1px solid #e4e7ed;
  padding-top: 15px;
}

.bill-dialog .el-table .el-button--text {
  padding: 2px 0;
}

.bill-dialog .el-pagination {
  margin-top: 15px;
  text-align: right;
}

.bill-dialog .el-table th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
}

.bill-dialog .el-table td {
  padding: 8px 0;
}

.bill-dialog .el-table .el-button--text {
  font-size: 12px;
}

.bill-dialog .el-form-item__label {
  font-weight: 500;
}

.bill-dialog .el-input__wrapper {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.bill-dialog .el-input__wrapper:hover {
  box-shadow: 0 0 0 1px #c0c4cc inset;
}

.bill-dialog .el-table .agent-name-cell {
  font-weight: 500;
  color: #409eff;
}

.bill-dialog .el-form-item__label {
  color: #606266;
}

.bill-dialog .amount-cell {
  font-family: "Courier New", monospace;
  font-weight: 500;
}

.bill-dialog .amount-positive {
  color: #67c23a;
}

.bill-dialog .amount-negative {
  color: #f56c6c;
}

.bill-dialog .amount-neutral {
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bill-dialog .el-dialog {
    width: 95% !important;
    margin: 5vh auto;
  }

  .bill-dialog .el-form--inline .el-form-item {
    display: block;
    margin-right: 0;
    margin-bottom: 15px;
  }

  .bill-dialog .el-table {
    font-size: 12px;
  }

  .bill-dialog .el-table .cell {
    padding: 5px;
  }
}
</style>